<?php

namespace App\Http\Controllers\Warehouse;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Chanjet\TplusCommonController;
use App\Http\Validate\Warehouse\Warehouse;
use App\Jobs\Manger;
use App\Models\Warehouse\WarehouseList;
use App\Models\Warehouse\WarehouseType;
use App\Services\Chanjet\ChanjetRequest;
use App\Services\Stock\Stock;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Stock\Stock as StockStock;

/**
 * 仓库管理
 */
class WarehouseController extends BaseController
{
    /**
     * 获取列表
     */
    public function getlist(Request $request)
    {
        //需获取当前用户所属账套
        $wtype = $request->wtype ?? 0;
        $status = $request->status ?? 0;
        $isgetall = $request->isgetall ?? 0;
        if ($wtype != 0) {
            $warehouse_type = WarehouseType::where([['id', $wtype]])->first();
            if (!$warehouse_type) {
                return response()->json(['code' => '001', 'msg' => '无效分类信息']);
            }
        }


        $list = WarehouseList::getList($request, $this->mangerinfo['cpid'], $wtype, $status, $isgetall);
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 仓库分类列表
     */
    public function gettypelist()
    {
        $list = WarehouseType::getTypeList();
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 新增仓库
     */
    public function dopostadd(Request $request)
    {
        $req_data = $request->only(['wtype', 'warehouse_no', 'warehouse_name']);

        $Validate = new Warehouse;
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $warehouse_type = WarehouseType::where([['id', $req_data['wtype']]])->first();
        if (!$warehouse_type) {
            return response()->json(['code' => '001', 'msg' => '无效分类信息']);
        }
        $isexist = WarehouseList::where([['warehouse_no', $req_data['warehouse_no']], ['cpid', $this->mangerinfo['cpid']]])->orWhere([['warehouse_name', $req_data['warehouse_name']], ['cpid', $this->mangerinfo['cpid']]])->first();

        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '仓库编码、仓库名称不允许重复']);
        }

        $data = [
            'cpid' => $this->mangerinfo['cpid'],
            'wtype' => $req_data['wtype'],
            'warehouse_no' => $req_data['warehouse_no'],
            'warehouse_name' => $req_data['warehouse_name'],
            'update_at' => time(),
            'manger_id'=>0
        ];
        $data['create_at'] = time();

        DB::beginTransaction();
        try {

            $insert_id = WarehouseList::create($data)->id;
            //是否需要同步库存增加记录数据

            Stock::syncStockByWarehouse($insert_id, $data, $this->mangerinfo['cpid']);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '新增失败' . $e->getMessage()]);
        }

        /*
         *  创建仓库
         *  01：普通仓  02：现场仓  03：委外仓
         *  2024.12.16
         *  客户没有 仓库类型概念, 统一设置 普通仓
         *
         * */
        $chanjet_param = [
            "dto" => [
                "Code" => $req_data['warehouse_no'],//仓库编码
                "Name" => $req_data['warehouse_name'],//仓库名称
                "WarehouseType" =>
                    ["code" => "01"]
            ]
        ];

        $requestData = [
            "api" => "WarehouseCreate",
            "param" => $chanjet_param,
            "mangerinfo" => $this->mangerinfo
        ];
        Manger::dispatch($requestData);

        return response()->json(['code' => '000', 'msg' => '新增成功']);
    }

    /**
     * 编辑--不允许编辑
     */
    public function dopostedit(Request $request)
    {
        return response()->json(['code' => '001', 'msg' => '不可编辑']);
    }

    /**
     * 冻结
     */
    public function changestatus(Request $request)
    {
        return response()->json(['code' => '001', 'msg' => '功能已废弃']);
        $id = $request->id ?? 0;
        $info = WarehouseList::where([['id', $id], ['cpid', $this->mangerinfo['cpid']]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $status = 2;
        WarehouseList::where([['id', $id]])->update(['status' => $status, 'update_at' => time()]);

        $count = StockStock::where([['cpid', $this->mangerinfo['cpid']], ['warehouse_id', $id]])
            ->where(function ($query) {
                $query->where([['can_use_weight', '<>', 0]])->orWhere([['current_pieces', '<>', 0]])
                    ->orWhere([['locked_weight', '<>', 0]])->orWhere([['locked_pieces', '<>', 0]]);
            })->count();
        if ($count > 0) {
            return response()->json(['code' => '001', 'msg' => '库存存在在库或者已锁定的库存，无法冻结']);
        }

        // StockStock::where(['warehouse_id' => $id])->update();



        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }
}
